package com.tepth.remote.control.service.task;

import android.support.annotation.Nullable;

import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/13
 */
public class ControlTimerTask {

    private TimerTaskCallback mCallback = null;

    private String showCalendar = null;

    private final ThreadUtils.Task<String> mTimerTask = new ThreadUtils.Task<String>() {
        @Nullable
        @Override
        public String doInBackground() throws Throwable {
            if (showCalendar != null) {
                final Date date = TimeUtils.string2Date(showCalendar);
                showCalendar = TimeUtils.date2String(addOneSecond(date));
            }
            return showCalendar;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void onSuccess(@Nullable String result) {
            if (mCallback != null) {
                mCallback.success(result);
            }
        }

        @Override
        public void onCancel() {
            if (mCallback != null) {
                mCallback.cancel();
            }
        }

        @Override
        public void onFail(Throwable t) {
            if (mCallback != null) {
                mCallback.cancel();
            }
        }
    };

    public static Date addOneSecond(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, 1);
        return calendar.getTime();
    }

    private static final class Holder {
        private static final ControlTimerTask INSTANCE = new ControlTimerTask();
    }

    public static ControlTimerTask getInstance() {
        return Holder.INSTANCE;
    }

    public ControlTimerTask setCallback(TimerTaskCallback callback) {
        mCallback = callback;
        return this;
    }

    public ControlTimerTask setShowCalendar(String showCalendar) {
        this.showCalendar = showCalendar;
        return this;
    }

    public ThreadUtils.Task getTimerTask() {
        return mTimerTask;
    }

}
